import React, { useState, useEffect } from 'react';
import {
  PlusIcon,
  PlayIcon,
  PauseIcon,
  StopIcon,
  TrashIcon,
  DocumentArrowDownIcon,
  EyeIcon,
  Cog6ToothIcon,
} from '@heroicons/react/24/outline';
import { Button } from '@components/ui';
import { useTauriCommand } from '@hooks/useTauri';
import { cn } from '@utils/index';
import toast from 'react-hot-toast';

interface CrawlerTask {
  id: string;
  name: string;
  url: string;
  status: 'idle' | 'running' | 'paused' | 'completed' | 'failed';
  progress: number;
  pagesFound: number;
  pagesCrawled: number;
  dataExtracted: number;
  createdAt: string;
  lastRun?: string;
}

const CrawlerTasks: React.FC = () => {
  const [tasks, setTasks] = useState<CrawlerTask[]>([]);
  const [, setShowCreateModal] = useState(false);
  // const [newTask] = useState({
  //   name: '',
  //   url: '',
  //   selectors: '',
  //   maxPages: 100,
  //   delay: 1000
  // });

  const { invoke: getTasks, loading: loadingTasks } =
    useTauriCommand('get_crawler_tasks');
  // const { invoke: createTask } = useTauriCommand('create_crawler_task');
  const { invoke: startTask, loading: startingTask } =
    useTauriCommand('start_crawler_task');
  const { invoke: pauseTask } = useTauriCommand('pause_crawler_task');
  const { invoke: stopTask } = useTauriCommand('stop_crawler_task');
  const { invoke: deleteTask } = useTauriCommand('delete_crawler_task');

  useEffect(() => {
    loadTasks();
  }, []);

  const loadTasks = async () => {
    try {
      const taskList = await getTasks();
      setTasks(taskList || []);
    } catch (error) {
      console.error('Failed to load tasks:', error);
    }
  };

  const handleStartTask = async (taskId: string) => {
    try {
      await startTask({ taskId });
      toast.success('Task started');
      await loadTasks();
    } catch (error) {
      toast.error('Failed to start task');
    }
  };

  const handlePauseTask = async (taskId: string) => {
    try {
      await pauseTask({ taskId });
      toast.success('Task paused');
      await loadTasks();
    } catch (error) {
      toast.error('Failed to pause task');
    }
  };

  const handleStopTask = async (taskId: string) => {
    try {
      await stopTask({ taskId });
      toast.success('Task stopped');
      await loadTasks();
    } catch (error) {
      toast.error('Failed to stop task');
    }
  };

  const handleDeleteTask = async (taskId: string) => {
    if (confirm('Are you sure you want to delete this task?')) {
      try {
        await deleteTask({ taskId });
        toast.success('Task deleted');
        await loadTasks();
      } catch (error) {
        toast.error('Failed to delete task');
      }
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'running':
        return 'text-green-600 bg-green-100 dark:bg-green-900 dark:text-green-300';
      case 'paused':
        return 'text-yellow-600 bg-yellow-100 dark:bg-yellow-900 dark:text-yellow-300';
      case 'completed':
        return 'text-blue-600 bg-blue-100 dark:bg-blue-900 dark:text-blue-300';
      case 'failed':
        return 'text-red-600 bg-red-100 dark:bg-red-900 dark:text-red-300';
      default:
        return 'text-gray-600 bg-gray-100 dark:bg-gray-700 dark:text-gray-300';
    }
  };

  return (
    <div className="mx-auto max-w-7xl">
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
            Crawler Tasks
          </h1>
          <p className="mt-1 text-gray-600 dark:text-gray-400">
            Manage and monitor your web crawling tasks
          </p>
        </div>
        <Button onClick={() => setShowCreateModal(true)}>
          <PlusIcon className="mr-2 h-4 w-4" />
          New Task
        </Button>
      </div>

      {/* Tasks Grid */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3">
        {tasks.map(task => (
          <div
            key={task.id}
            className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800"
          >
            {/* Task Header */}
            <div className="mb-4 flex items-start justify-between">
              <div className="flex-1">
                <h3 className="mb-1 text-lg font-semibold text-gray-900 dark:text-gray-100">
                  {task.name}
                </h3>
                <p className="truncate text-sm text-gray-500 dark:text-gray-400">
                  {task.url}
                </p>
              </div>
              <span
                className={cn(
                  'rounded-full px-2 py-1 text-xs font-medium',
                  getStatusColor(task.status)
                )}
              >
                {task.status}
              </span>
            </div>

            {/* Progress Bar */}
            <div className="mb-4">
              <div className="mb-1 flex justify-between text-sm text-gray-600 dark:text-gray-400">
                <span>Progress</span>
                <span>{task.progress}%</span>
              </div>
              <div className="h-2 w-full rounded-full bg-gray-200 dark:bg-gray-700">
                <div
                  className="h-2 rounded-full bg-blue-600 transition-all duration-300"
                  style={{ width: `${task.progress}%` }}
                ></div>
              </div>
            </div>

            {/* Stats */}
            <div className="mb-4 grid grid-cols-3 gap-4 text-center">
              <div>
                <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
                  {task.pagesCrawled}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Crawled
                </p>
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
                  {task.pagesFound}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Found
                </p>
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
                  {task.dataExtracted}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Extracted
                </p>
              </div>
            </div>

            {/* Actions */}
            <div className="flex items-center justify-between">
              <div className="flex space-x-2">
                {task.status === 'idle' || task.status === 'paused' ? (
                  <Button
                    size="sm"
                    onClick={() => handleStartTask(task.id)}
                    loading={startingTask}
                  >
                    <PlayIcon className="h-4 w-4" />
                  </Button>
                ) : task.status === 'running' ? (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handlePauseTask(task.id)}
                  >
                    <PauseIcon className="h-4 w-4" />
                  </Button>
                ) : null}

                {task.status === 'running' || task.status === 'paused' ? (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleStopTask(task.id)}
                  >
                    <StopIcon className="h-4 w-4" />
                  </Button>
                ) : null}
              </div>

              <div className="flex space-x-2">
                <Button size="sm" variant="ghost">
                  <EyeIcon className="h-4 w-4" />
                </Button>
                <Button size="sm" variant="ghost">
                  <DocumentArrowDownIcon className="h-4 w-4" />
                </Button>
                <Button size="sm" variant="ghost">
                  <Cog6ToothIcon className="h-4 w-4" />
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => handleDeleteTask(task.id)}
                  className="text-red-600 hover:text-red-700"
                >
                  <TrashIcon className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Empty State */}
      {tasks.length === 0 && !loadingTasks && (
        <div className="py-12 text-center">
          <div className="mx-auto mb-4 flex h-24 w-24 items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800">
            <PlusIcon className="h-12 w-12 text-gray-400" />
          </div>
          <h3 className="mb-2 text-lg font-medium text-gray-900 dark:text-gray-100">
            No crawler tasks yet
          </h3>
          <p className="mb-4 text-gray-500 dark:text-gray-400">
            Create your first crawling task to get started
          </p>
          <Button onClick={() => setShowCreateModal(true)}>
            <PlusIcon className="mr-2 h-4 w-4" />
            Create Task
          </Button>
        </div>
      )}
    </div>
  );
};

export default CrawlerTasks;
